package com.imagefake.service.impl;

import com.imagefake.entity.SysUser;
import com.imagefake.mapper.SysMenuMapper;
import com.imagefake.mapper.SysUserMapper;
import com.imagefake.vo.SecurityUser;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 使用MySQL用户表来进行用户登录验证
 */
@Service
public class SecurityUserServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        SysUser sysUser = sysUserMapper.getByUserName(username);
        if (null == sysUser) {
            throw new UsernameNotFoundException("账号不存在");
        }
        SecurityUser securityUser = new SecurityUser(sysUser);
        // 设置用户的权限
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = sysMenuMapper
                .queryPermissionByUserId(sysUser.getUserId())
                .stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        securityUser.setSimpleGrantedAuthorities(simpleGrantedAuthorities);
        return securityUser;
    }


}
